package org.zjx.resolution;

import lombok.Data;
import org.zjx.common.entity.Rect;
import org.zjx.resource.ResourceManager;

import java.util.HashMap;
import java.util.Map;

@Data
public abstract class AbstractScreenResolution implements IScreenResolution {
    protected String gameResName; //资源名称
    protected Rect originBounds; //原始界面区域
    protected String refImage; // 参考（标题） 图片
    protected Rect refImageArea; // 参考图片在界面区域 ，逆推界面区域
    protected Map<String, Object> properties = new HashMap<>();
    protected Map<String, ResolutionAttributes> attributesArea = new HashMap<>();
    protected Map<String, ResolutionButton> buttonsArea = new HashMap<>();

    //    // 添加注解忽略类型信息
//    @JSONField(serialize = false, deserialize = false)
    // 实现接口方法
    @Override
    public Map<String, Object> getProperties() {
        return properties;
    }

    @Override
    public Map<String, ResolutionAttributes> getAttributesArea() {
        return attributesArea;
    }

    @Override
    public Map<String, ResolutionButton> getButtonsArea() {
        return buttonsArea;
    }


    protected abstract void setDefaultValues();

    protected abstract boolean needTheme();

    protected int loadCount = 0;

    /**
     * 加载分辨率配置
     * @return 是否成功加载配置
     */
    public boolean loadResolution() {
        try {
            IScreenResolution loadedConfig =  loadResolution(needTheme()? ResourceManager.CONFIG.theme():null);

            // 如果加载成功，复制配置到当前对象
            if (loadedConfig != null) {
                copyFrom(loadedConfig);
                return true;
            }
        } catch (Exception e) {
            // 记录日志而不是忽略异常
            // 加载失败时设置默认值
            if (loadCount > 1) return false;
            loadCount++;
            setDefaultValues();
            return loadResolution();
        }

        return false;
    }

    /**
     * 从另一个配置对象复制数据
     * @param source 源配置对象
     */
    private void copyFrom(IScreenResolution source) {
        this.setGameResName(source.getGameResName());
        this.setOriginBounds(source.getOriginBounds());
        this.setRefImage(source.getRefImage());
        this.setRefImageArea(source.getRefImageArea());
        this.setProperties(new HashMap<>(source.getProperties()));
        this.setAttributesArea(new HashMap<>(source.getAttributesArea()));
        this.setButtonsArea(new HashMap<>(source.getButtonsArea()));
    }

    /**
     * 保存默认配置到文件
     */
    public void saveDefaultConfiguration() {
        try {
            saveResolution(needTheme()? ResourceManager.CONFIG.theme():null);
        } catch (Exception e) {
            System.err.println("保存默认配置失败: " + e.getMessage());
        }
    }
}